<template>
  <div>
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <el-button
            v-auth="`/system/notice-add`"
            type="primary"
            @click="handleAdd"
            class="add-option"
            >新增</el-button
          >
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="标题" prop="titleLike">
              <el-input
                v-model.trim="formInline.titleLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建人" prop="createUserNameLike">
              <el-input
                v-model.trim="formInline.createUserNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建时间" prop="">
              <el-date-picker
                class="width-custom220"
                v-model="timeValue"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleChangeDate"
              />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="companyNameLike">
              <el-input
                v-model.trim="formInline.companyNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item> -->
            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="state.tableData"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="title" label="标题内容"></el-table-column>
            <el-table-column prop="msgType" label="消息类型">
              <template #default="{ row }">
                {{ formatterType(row) }}
              </template>
            </el-table-column>
            <el-table-column prop="msgLevel" label="紧急程度">
              <template #default="{ row }">
                <div
                  class="labelFlag"
                  :class="infoUrgentMap.get(row.msgLevel)"
                ></div>
                {{ formatterUrgentType(row) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="createUserName"
              label="创建人"
            ></el-table-column>

            <el-table-column
              prop="createTime"
              label="创建时间"
            ></el-table-column>
            <el-table-column
              prop="publishTime"
              label="发布时间"
            ></el-table-column>
            <!-- <el-table-column
              prop="publishEndTime"
              label="停用时间"
            ></el-table-column> -->
            <el-table-column prop="" label="状态">
              <template #default="{ row }">
                {{ formatterStatusType(row) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-auth="`/system/notice-edit`"
                  type="text"
                  @click="handleEdit(row)"
                  >编辑</el-button
                >

                <template v-if="row.publishType !== '1'">
                  <el-button
                    v-auth="`/system/notice-publish`"
                    type="text"
                    @click="handlePublish(row)"
                    >发布</el-button
                  >
                </template>
                <template v-else>
                  <el-button
                    v-auth="`/system/notice-publish`"
                    type="text"
                    @click="handleUnPublish(row)"
                    >撤回</el-button
                  >
                </template>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button v-auth="`/system/notice-del`" type="text"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import {
  postMessageList,
  postMessageDelete,
  postMessageUpdate
} from "/@/api/notice";
import NotifMessage from "/@/utils/message/notification";
import { useRouter } from "vue-router";
// import RePagination from "/@/components/RePagination/index.vue";

import {
  InfoStatusMap,
  InfoTypeMap,
  infoUrgentMap,
  infoUrgentType
} from "./types";

interface formInlineType {
  titleLike: string;
  createUserNameLike: string;
  createTimeStrStart: string;
  createTimeStrEnd: string;
  pageSize: number;
  pageNum: number;
}

const router = useRouter();
const formRef = ref<HTMLFormElement | null>(null) as any;
let loading = ref<boolean>(false);
let total = ref<number>(0);

let timeValue = ref(null);

let formInline = reactive<formInlineType>({
  titleLike: "",
  createUserNameLike: "",
  createTimeStrStart: "",
  createTimeStrEnd: "",
  pageSize: 10,
  pageNum: 1
});
// let mode = ref<string>("add");
let state = reactive({
  tableData: [],
  companyInfo: {}
});

// 请求公司列表表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    const { code, data } = await postMessageList(obj);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}
// 打开添加人员弹窗
const handleAdd = (): void => {
  router.push({ path: "/system/notice/detail", query: { mode: "add" } });
};

// 操作
// const onEmitSubmit = (isSubmit: boolean) => {
//   dialogFormVisible.value = false;
//   if (isSubmit) {
//     getTableData();
//   }
// };

// 清除表单，重置
const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  handleChangeDate(null);
};

// 根据条件进行搜索
const handleSearch = (): void => {
  getTableData(formInline);
};

const handleChangeDate = item => {
  console.log(item, "date");
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

// 删除记录
const handleDelete = async item => {
  try {
    const { code, message } = await postMessageDelete({ id: item.id });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleEdit = row => {
  router.push({
    path: "/system/notice/detail",
    query: { id: row.id, mode: "edit" }
  });
};

const handlePublish = async row => {
  try {
    const { code, message } = await postMessageUpdate({
      id: row.id,
      publishType: "1"
    });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleUnPublish = async row => {
  try {
    const { code, message } = await postMessageUpdate({
      id: row.id,
      publishType: "2"
    });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const formatterStatusType = row => {
  if (!row.publishType) return "-";
  return InfoStatusMap.get(row.publishType);
};

const formatterType = row => {
  if (!row.msgType) return "-";
  return InfoTypeMap.get(row.msgType);
};

const formatterUrgentType = row => {
  if (!row.msgLevel) return "-";
  return infoUrgentType[row.msgLevel - 1].key;
};

// 请求数据
getTableData(formInline);
</script>

<style lang="scss" scoped>
.tableSrc {
  width: 100px;
}

.labelFlag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.margin-right {
  margin-right: 8px;
}
.red {
  background: red;
  @extend .margin-right;
}
.yellow {
  background: yellow;
  @extend .margin-right;
}
.gray {
  background: gray;
  @extend .margin-right;
}
</style>
